package com.sz.sboot.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

//写一个工具类； 专门用来处理Http中的get,post请求！
public class HttpClientUtils {


    //专门用来处理Http中的get请求！
    public static String  getMethod(String url){
        String result = "";
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);   //相当于是在浏览器地址栏中输入了一个url地址后回车！
        try {
            HttpResponse response = client.execute(get);
            System.out.println(response.getStatusLine());   //200
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();//释放get请求；
        }
        return result;
    }


    //写一个工具类； 专门用来处理Http中的post请求！
    public static String  postMethod(String url,String json){
        String result = "";
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);   //相当于是表单提交；
        try {
            StringEntity se = new StringEntity(json,"UTF-8");
            post.setHeader("Content-Type","application/json;charset=UTF-8");
            post.setEntity(se);
            HttpResponse response = client.execute(post);
            System.out.println(response.getStatusLine());   //200
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();//释放get请求；
        }
        return result;
    }

    public static void main(String[] args) {
        /*for (int i = 3429; i <=3431 ; i++) {
            //测试get请求；
            String result = getMethod("http://10.1.12.103:9999/area/delete/"+i);
            System.out.println(result);
        }*/

        //测试post请求；
       /* for (int i = 1; i < 100000; i++) {
            String  url = "http://10.1.12.103:9999/area/save";
            String json = "{\n" +
                    "    \"level\": 1,\n" +
                    "    \"name\": \"台湾省"+i+"\",\n" +
                    "    \"pid\": 1\n" +
                    "}";
            String result = postMethod(url, json);
            System.out.println(result);
        }*/

        //测试get请求；
        String result = getMethod("http://localhost:7508/tuser/getUsersById/46");
        System.out.println(result);
    }
}
